package com.webdrider.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.common.model.util.UserType;
import com.common.security.exceptions.ConverterException;

public class Converter {

	private Converter() {}
	
	public static Long convertToLong(String value) throws ConverterException {
		try {
			return new Long(value);
		} catch (Exception e) {
			throw new ConverterException(ConverterException.CONVERTER_EXCEPTION);
		}
	}
	
	public static Long convertDateToLong(String value) throws ConverterException {
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(dateFormat.parse(value));
			
			return ((long) calendar.get(Calendar.YEAR)) * 100000000 +
					(calendar.get(Calendar.MONTH) + 1) * 1000000 +
					calendar.get(Calendar.DATE) * 10000 +
					calendar.get(Calendar.HOUR_OF_DAY) * 100 +
					calendar.get(Calendar.MINUTE);
		} catch (ParseException e) {
			throw new ConverterException(ConverterException.CONVERTER_EXCEPTION);
		}
	}
	
	public static Date convertToDate(String value) throws ConverterException {
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
			return dateFormat.parse(value);
		} catch (ParseException e) {
			throw new ConverterException(ConverterException.CONVERTER_EXCEPTION);
		}
	}
	
	public static String convertDateToString(Long value) {
		StringBuilder builder = new StringBuilder();
		
		builder.append((value / 1000000) % 100);
		builder.append("-");
		builder.append((value / 10000) % 100);
		builder.append("-");
		builder.append(value / 100000000);
		builder.append(" ");
		builder.append((value / 100) % 100);
		builder.append(":");
		builder.append(value % 100);
		
		return builder.toString();
	}
	
	public static UserType convertToUserType(String value) throws ConverterException {
		try {
			return UserType.valueOf(value);
		} catch (IllegalArgumentException argumentException) {
			throw new ConverterException(ConverterException.CONVERTER_EXCEPTION);
		}
	}
}